package com.banshuibao.bsb_android.download;

import java.io.File;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;

import com.banshuibao.bsb_android.MyApplication;
import com.banshuibao.bsb_android.model.DownloadInfo;
import com.banshuibao.bsb_android.util.CCMediaConfig;
import com.banshuibao.bsb_android.util.DataSet;
import com.banshuibao.bsb_android.util.MediaUtil;
import com.banshuibao.bsb_android.util.ParamsUtil;
import com.bokecc.sdk.mobile.download.DownloadListener;
import com.bokecc.sdk.mobile.download.Downloader;
import com.bokecc.sdk.mobile.exception.DreamwinException;

/**
 * DownloadService，用于支持后台下载
 *
 * @author CC视频
 */
public class DownloadService extends Service {

    private Downloader downloader;
    private File file;
    private String title;
    private String videoId;
    private int progress;
    private String progressText;
    private MyReceiver myReceiver;

    private boolean stop = true;
    private DownloadBinder binder = new DownloadBinder();

    public class DownloadBinder extends Binder {

        public String getTitle() {
            return title;
        }

        public int getProgress() {
            return progress;
        }

        public String getProgressText() {
            return progressText;
        }

        public boolean isStop() {
            return stop;
        }

        public void pause() {
            if (downloader == null) {
                return;
            }
            downloader.pause();
        }

        public void download() {
            if (downloader == null) {
                return;
            }

            if (downloader.getStatus() == Downloader.WAIT) {
                downloader.start();
            }

            if (downloader.getStatus() == Downloader.PAUSE) {
                downloader.resume();
            }
        }

        public void cancel() {

            if (downloader == null) {
                return;
            }

            downloader.cancel();
        }

        public int getDownloadStatus() {
            if (downloader == null) {
                return Downloader.WAIT;
            }

            return downloader.getStatus();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, new IntentFilter(CCMediaConfig.ACTION_DOWNLOADING_CANCEL));
    }

    private String getVideoId(String title) {
        if (title == null) {
            return null;
        }

        int charIndex = title.indexOf('-');

        if (-1 == charIndex) {
            return title;
        } else {
            return title.substring(0, charIndex);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent == null) {
            return Service.START_STICKY;
        }

        if (downloader != null) {
            return Service.START_STICKY;
        }

        title = intent.getStringExtra("title");
        if (title == null) {
            return Service.START_STICKY;
        }

        videoId = getVideoId(title);
        if (videoId == null) {
            return Service.START_STICKY;
        }

        //downloader = DownloadFragment.downloaderHashMap.get(title);
        if (downloader == null) {
            String userId = MyApplication.applicationInstance.getLoginInfo().getUserId();
            file = MediaUtil.createFile(CCMediaConfig.DOWNLOAD_DIR + userId, title);
            if (file == null) {
                return Service.START_STICKY;
            }
            downloader = new Downloader(file, videoId, CCMediaConfig.USER_ID, CCMediaConfig.APP_KEY);
            //DownloadFragment.downloaderHashMap.put(title, downloader);
        }

        downloader.setDownloadListener(downloadListener);
        downloader.start();

        Intent notifyIntent = new Intent(CCMediaConfig.ACTION_DOWNLOADING);
        notifyIntent.putExtra("status", Downloader.WAIT);
        notifyIntent.putExtra("title", title);
        sendBroadcast(notifyIntent);

        stop = false;

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {

        if (downloader != null) {
            downloader.cancel();
            resetDownloadService();
        }
        super.onTaskRemoved(rootIntent);
    }

    private int STATUS;

    private DownloadListener downloadListener = new DownloadListener() {

        @SuppressWarnings("deprecation")
        @Override
        public void handleStatus(String videoId, int status) {
            STATUS = status;
            Intent intent = new Intent(CCMediaConfig.ACTION_DOWNLOADING);
            intent.putExtra("status", status);
            intent.putExtra("title", title);

            updateDownloadInfoByStatus(status);

            switch (status) {
                case Downloader.PAUSE:
                    sendBroadcast(intent);
                    break;
                case Downloader.DOWNLOAD:
                    sendBroadcast(intent);
                    break;
                case Downloader.FINISH:
                    DataSet.saveData();
                    // 停掉服务自身
                    stopSelf();
                    // 重置下载服务
                    resetDownloadService();
                    // 通知已下载队列
                    sendBroadcast(new Intent(CCMediaConfig.ACTION_DOWNLOADED));
                    // 通知下载中队列
                    sendBroadcast(intent);
                    //移除完成的downloader
                    //DownloadFragment.downloaderHashMap.remove(title);
                    break;
            }
        }

        @Override
        public void handleProcess(long start, long end, String videoId) {
            if (stop) {
                return;
            }
            progress = (int) ((double) start / end * 100);
            if (progress <= 100) {
                progressText = ParamsUtil.byteToM(start).
                        concat(" M / ").
                        concat(ParamsUtil.byteToM(end).
                                concat(" M"));
            }
            updateDownloadInfoByStatus(STATUS);
        }

        @Override
        public void handleException(DreamwinException exception, int status) {
            STATUS = status;
            // 停掉服务自身
            stopSelf();

            updateDownloadInfoByStatus(status);

            Intent intent = new Intent(CCMediaConfig.ACTION_DOWNLOADING);
            intent.putExtra("errorCode", exception.getErrorCode().Value());
            intent.putExtra("title", title);
            sendBroadcast(intent);
        }

        @Override
        public void handleCancel(String videoId) {

            stopSelf();
            resetDownloadService();
        }
    };

    private void resetDownloadService() {
        progress = 0;
        progressText = null;
        downloader = null;
        stop = true;
    }

    private void updateDownloadInfoByStatus(int status) {
        DownloadInfo downloadInfo = DataSet.getDownloadInfo(title);
        if (downloadInfo == null) {
            return;
        }
        downloadInfo.setStatus(status);

        if (progress > 0) {
            downloadInfo.setProgress(progress);
        }

        if (progressText != null) {
            downloadInfo.setProgressText(progressText);
        }

        DataSet.updateDownloadInfo(downloadInfo);
    }

    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //退出下载
            if (downloader != null) {
                downloader.cancel();
                resetDownloadService();
                DataSet.saveData();
                stopSelf();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DataSet.saveData();
        unregisterReceiver(myReceiver);
    }
}
